package cn.zbmao.web.controller;

import cn.zbmao.web.bean.Constants;
import cn.zbmao.web.bean.Territory;
import cn.zbmao.web.bean.User;
import cn.zbmao.web.services.QualificationServices;
import cn.zbmao.web.services.UserServices;
import cn.zbmao.web.util.DateUtil;
import cn.zbmao.web.util.FormText;
import cn.zbmao.web.util.HighlightToText;
import cn.zbmao.web.util.StringOperateUtil;
import cn.zbmao.web.util.dao.DaoFactory;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import java.util.*;

public class SearchController extends Controller {
	public void index() {
		int tender_type = getParaToInt("tender_type",-1);

		String search_key = getPara("search_key","");
        search_key= Jsoup.clean(StringOperateUtil.exChange(search_key), Whitelist.basic());
        search_key=StringOperateUtil.exChange(FormText.text(search_key));
        String search_key_hi=search_key;
        setAttr("search_key",search_key);
        search_key=StringOperateUtil.returnKey(search_key);
		String timeOne = getPara("timeOne","");
		String timeTwo = getPara("timeTwo","");
		Integer pages = getParaToInt("p", 0);
		String search_subscriber = getPara("search_subscriber","");
        search_subscriber= Jsoup.clean(StringOperateUtil.exChange(search_subscriber), Whitelist.basic());
        search_subscriber=FormText.text(search_subscriber);
		Integer territory = getParaToInt("territory",0);
        //过期与否
        Integer isOverdue = getParaToInt("isOverdue",0);
        //排序
        Integer orderby = getParaToInt("orderby",1);
        //搜索正文还是标题
        Integer search_type = getParaToInt("search_type",1);
        //金额
        Integer itemAmount=getParaToInt("itemAmount",0);
        //资质
        Integer qualification=getParaToInt("qualification",0);
        //地域
        Integer location=getParaToInt("location1",0);
        if(location==0){
            location=getParaToInt("location",0);
        }
        //模块
        Integer hiden=getParaToInt("hiden",0);
        Integer iss=0;
        if(tender_type==-1&&search_key.equals("")&&search_subscriber.equals("")&&territory==0
                &&isOverdue==0&&search_type==1&&itemAmount==0&&qualification==0&&location==0){
            iss=1;
        }
        if(tender_type==-1) {
            tender_type = 0;
        }

        int bi=getParaToInt("bi",0);

		User user = (User) getSessionAttr("user");

        int title_key_order=0;

        int sTime_order=0;

        int eTime_order=0;

        int qualification_order=0;

        int subscriber_order=0;

        int agent_order=0;

        int itemAmount_order=0;

        int tenderId_order=0;

        int time_order=0;

        int winBidCompany_order=0;

        int winBidFigure_order=0;

        int bian=getParaToInt("bian",0);
        if(pages!=0){
            if(bi==0){
                bi=bian;
            }else{
                bi=0;
            }
        }
//搜索页面排序，为1时正序，为2时倒序，
        if(bian==1){
            if(bi==1){
                title_key_order = 2;
            }else {
                title_key_order = 1;
            }

                if (bi != 1) {
                    bi = 1;
                } else {
                    bi = 0;
                }


        }else if(bian==2){
            if(bi==2){
                eTime_order=2;
                tenderId_order=2;
            }else {
                eTime_order=1;
                tenderId_order=1;
            }
            if(bi!=2){
                bi=2;
            }else{
                bi=0;
            }


        }else if(bian==3){
            if(bi==3){
                qualification_order=2;
                time_order=2;
            }else {
                qualification_order=1;
                time_order=1;
            }

            if(bi!=3){
                bi=3;
            }else{
                bi=0;
            }

        }else if(bian==4){
            if(bi==4){
                itemAmount_order=2;
                winBidCompany_order=2;
            }else {
                itemAmount_order=1;
                winBidCompany_order=1;
            }

            if(bi!=4){
                bi=4;
            }else{
                bi=0;
            }

        }else if(bian==5){
            if(bi==5){
                subscriber_order=2;
                winBidFigure_order=2;
            }else {
                subscriber_order=1;
                winBidFigure_order=1;
            }

            if(bi!=5){
                bi=5;
            }else{
                bi=0;
            }

        }else if(bian==6){
            if(bi==6){
                agent_order=2;
            }else {
                agent_order=1;
            }

            if(bi!=6){
                bi=6;
            }else{
                bi=0;
            }

        }
            if(pages==0){
                pages=1;
            }

        setAttr("bi",bi);

        setAttr("itemAmount",itemAmount);

        setAttr("bian",bian);


		int startTime = 0;
		int endTime = 0;

		if (!timeOne.isEmpty()) {
			startTime = DateUtil.getStringToInt("yyyy-MM-dd", timeOne);
		}
		if (!timeTwo.isEmpty()) {
			endTime = DateUtil.getStringToInt("yyyy-MM-dd", timeTwo) + 60 * 60 * 24;
		}
		if (startTime>=endTime&&!timeOne.isEmpty()) {
			setAttr("error", 0);
			setAttr("errormsg", "时间输入有误！请重新选择时间！");
		}else{
			setAttr("error", 1);
		}
		
		setAttr("territorys", Territory.getTerritorys());
		
		//获取当前时间
		int nowtime= DateUtil.getTodayToInt()-1;





        setAttr("user",user);
        setAttr("title",search_key_hi+"-搜索-招标信息");
        setAttr("param","user-setting");


        setAttr("tender_type",tender_type);
        setAttr("timeOne",timeOne);
        setAttr("timeTwo",timeTwo);
        setAttr("search_subscriber",search_subscriber);
        setAttr("territory",territory);
        setAttr("isOverdue",isOverdue);
        setAttr("orderby",orderby);
        setAttr("endTime_order",eTime_order);
        setAttr("search_type",search_type);
        setAttr("qualification",qualification);
        setAttr("location",location);


//        List<Record> locationList = null;
		Page<Record> newsPage = null;
        Page<Record> newPageAnd=null;
        List<String> relatedWords =new  ArrayList<String>() ;

//        Record qualificationStr=DaoFactory.getQualificationDao().findByIdWithIsOk(qualification);

        List<Record>qualificationList=DaoFactory.getQualificationDao().findQualificationList();
        setAttr("qualificationList",qualificationList);

        List <Record>IndustryList= DaoFactory.getNewsDao().find_industry(1);
        setAttr("IndustryList",IndustryList);

        List<Record>locations=DaoFactory.getLocationDao().getLocationList();
        List<Record>url_list1 =DaoFactory.getLocationDao().getLocationList_u();
//        List<Record>url_list1 = DaoFactory.getUserDao().getUser_district_un(user.getInt("id"));
//        List<Record>locations=DaoFactory.getUserDao().getUser_district_u(user.getInt("id"));
        for(Record record:url_list1){
            locations.add(record);
        }
        setAttr("locations",locations);

        String [] qualifica=null;
        if(qualification>0){
           qualifica=QualificationServices.getQualificationMap().get(qualification).getSeachTerm();
            if(qualifica==null){
                qualifica=new String[]{QualificationServices.getQualificationMap().get(qualification).getName()};
            }
        }

        List<String> r=new ArrayList<String>();
        if(qualifica!=null) {
//            r = QualificationServices.getQualificationMap().get(qualification).getName();
            r= Arrays.asList(qualifica);
        }
        Record loca=DaoFactory.getLocationDao().findLevel(location);
        if(loca!=null) {
//            Record rc=DaoFactory.getLocationDao().findById(loca.getInt("parentid"));
//            if(rc!=null) {
//                loca.set("pid", rc.get("code"));
//            }

            if(loca.getInt("parentid")==0){
                setAttr("shen",loca.get("code"));
                setAttr("shi",0);
            }else{
                setAttr("shi",loca.get("code"));
                Record re=DaoFactory.getLocationDao().findById(loca.getInt("parentid"));
                setAttr("shen", re.get("code"));
            }
//
        }
        List<Record>modul=DaoFactory.getUserDao().findModulesByUserId(user.getInt("id"));
        setAttr("modul",modul);
        //招标信息
		if (tender_type==0) {
            //关注地域
            List<Record> district =  DaoFactory.getUserDao().getUser_district(user.getInt("id"));

            //资质
//            List<String> quallist = DaoFactory.getUserDao().findUserQualificationNameAllStr(user.getInt("id"));

//            if (district!=null&&district.size()==1){
//                locationList = DaoFactory.getLocationDao().getLocationList(district.get(0).getInt("district_id"));
//            }else{
//                locationList = new ArrayList<Record>();
//            }
//通过公户提交的表单，查询用户关注的数据
            if(iss!=1){
			newsPage = DaoFactory.getNewsDao().search_list(pages, 50,title_key_order,sTime_order,eTime_order,qualification_order,subscriber_order,agent_order,itemAmount_order,
					search_key, search_subscriber, startTime, endTime,itemAmount,
					tender_type,territory,isOverdue,orderby,search_type,qualifica,location);

			List<Record> newsList = newsPage.getList();
			for (Record record : newsList) {

				if (search_key.isEmpty()) {
					record.set("title_key", record.get("title"));
				} else {
//                    String search= StringOperateUtil.reString(search_key);
//                    String[] str=search.split(" ");
                    List<String> list = StringOperateUtil.getKeyword(search_key_hi);

                    int size =list.size();
                    String[] str = new String[size];
                    for(int i=0;i<list.size();i++){
                        str[i]=list.get(i);
                    }
                    record.set("title_key",HighlightToText.highlight(StringOperateUtil.exChange(record.getStr("title")),str));


                }
				if (record.getInt("stime") == 0) {
					record.set("startTime", "");
				}
				if (record.getInt("etime") == 0) {
					record.set("endTime", "");
				}
                if(record.get("qualification")==null) {
                    record.set("qualification","");
                }
//                为资质添加高亮
                if(r!=null){
//                  record.set("qualification",HighlightToText.highligthQualification(record.get("qualification").toString(),r));
                    record.set("qualification",QualificationServices.getQualificationForShow(record.get("qualification").toString(),r));
                }else{
                  record.set("qualification",HighlightToText.highligthQualification(record.get("qualification").toString(),""));
                }
//                record.set("qualification", QualificationServices.getQualificationForShow(record.get("qualification").toString(), qua));
                //截止日期小于当前时间未过期
				if (record.getInt("etime")>nowtime) {
					record.set("status", "<span class=\"highlight_gree hot\">[未过期]</span>");
				}else{
					record.set("status", "<span class=\"highlight hot\">[过期]</span>");
				}
				record.set("hostName", Constants.getHostMap().get(record.getInt("host_id")));
			}
            }
//推荐信息
//            newPageAnd= DaoFactory.getNewsDao().search_list_and(1, 8,
//                    search_subscriber, startTime, endTime,
//                    UserServices.getUserInfo(user.getInt("id")),tender_type,territory,isOverdue,search_type);
             List<Record> newsPageAnd= DaoFactory.getNewsDao().search_list_and(nowtime,endTime, UserServices.getUserInfo(user.getInt("id")));
//            List<Record> newsList1 = newPageAnd.getList();
            for (Record record : newsPageAnd) {


               record.set("title_key", record.get("title"));

                if (record.getInt("stime") == 0) {
                    record.set("startTime", "");
                }
                if (record.getInt("etime") == 0) {
                    record.set("endTime", "");
                }
//                if(record.get("qualification")==null) {
//                    record.set("qualification","");
//                }
//                if(r!=null){
//                    record.set("qualification",HighlightToText.highligthQualification(record.get("qualification").toString(),r.getStr("name")));
//                }else{
//                    record.set("qualification",HighlightToText.highligthQualification(record.get("qualification").toString(),""));
//                }
                if (record.getInt("etime")>nowtime) {
                    record.set("status", "<span class=\"highlight_gree hot\">[未过期]</span>");
                }else{
                    record.set("status", "<span class=\"highlight hot\">[过期]</span>");
                }
                record.set("hostName", Constants.getHostMap().get(record.getInt("host_id")));
            }
            setAttr("newsPageAnd",newsPageAnd);



            int time_last_login = DateUtil.getDateToInt(user
                    .getTimestamp("user_lastlogin_time"));

			setAttr("time_last_login", time_last_login);
			setAttr("newsPage", newsPage);
//            setAttr("locationList",locationList);
            setAttr("hiden",hiden);
            search_key_hi = search_key_hi.replace("+", "%2B");
            setAttr("search_key_hi",search_key_hi);
			render("/views/search/search.html");
//            render("/views/account/error.html");
		}else if(tender_type == 1){
//           中标数据查询

			newsPage = DaoFactory.getNewsDao().search_result_list(pages, 50,title_key_order,tenderId_order,time_order,winBidCompany_order,winBidFigure_order,
					search_key, search_subscriber, startTime, endTime,itemAmount,
					location);

			List<Record> newsList = newsPage.getList();


			for (Record record : newsList) {

				if (search_key_hi.isEmpty()) {
					record.set("title_key", record.get("title"));
				} else {
                    String search= StringOperateUtil.reString(search_key_hi);
                    String[] str=search.split(" ");
                    record.set("title_key",HighlightToText.highlight(StringOperateUtil.exChange(record.getStr("title")),str));
//					record.set("title_key", HighlightToText.highlight(
//                            record.getStr("title"), search_key));
				}
				if (record.getInt("successful_time") == 0) {
					record.set("time", "");
				}
				
			}

            //setAttr("locationList",locationList);
//            setAttr("search_key",search_key);
            search_key_hi = search_key_hi.replace("+", "%2B");
            setAttr("search_key_hi",search_key_hi);
			setAttr("newsPage", newsPage);
            setAttr("hiden",hiden);
			render("/views/search/news_result_search.html");
		}else{
			renderHtml("<h1>请勿瞎操作！</h1>");
		}
				
		
	}

    /**
     * 类别查询
     */
    public void IndustryListAjax(){
        //类别
        int idust=getParaToInt("idust",0);
        int level=getParaToInt("level",0);
        List<Record> IndustryList2=null;
        if(idust!=0) {
            IndustryList2 = DaoFactory.getNewsDao().find_industry_parentId(level, idust);
            setAttr("industryList2", IndustryList2);
        }

        render(new JsonRender().forIE());
    }



    public void json(){
    }

    /**
     * 添加模板
     */
    public void modul_add(){
        User user = (User) getSessionAttr("user");
//        传参 Jsoup.clean(StringOperateUtil.exChange(old_password), Whitelist.basic());
        String name_d=Jsoup.clean(getPara("name_d","".trim()), Whitelist.basic());
        String keyword_d=Jsoup.clean(getPara("keyword_d","").trim(), Whitelist.basic());
        Integer search_type_d=getParaToInt("search_type_d",0);
        Integer tender_type_d=getParaToInt("tender_type_d",0);
        Integer isOverdue_d=getParaToInt("isOverdue_d",0);
        String search_subscriber_d=Jsoup.clean(getPara("search_subscriber_d","").trim(), Whitelist.basic());
        Integer location_d=getParaToInt("location_d",0);
        Integer itemAmount_d=getParaToInt("itemAmount_d",0);
        Integer qualification_d=getParaToInt("qualification_d",0);
        Record record=DaoFactory.getUserDao().findModulesByName(user.getInt("id"),name_d);

        if(record!=null){
            setAttr("msg",1);

        }else if(name_d.length()>15){
            setAttr("msg",3);
        }else {
//            添加成功后，返回添加的数据
            if(DaoFactory.getUserDao().addModules(user.getInt("id"),name_d,keyword_d,search_type_d,tender_type_d,isOverdue_d,search_subscriber_d
                ,location_d,itemAmount_d,qualification_d)){
               Record record1= DaoFactory.getUserDao().findModulesByName(user.getInt("id"),name_d);
                setAttr("id1",record1.getInt("id"));
                setAttr("msg", 0);
            }else{
            setAttr("msg",2);
            }
        }
         render(new JsonRender().forIE());
    }

    /**
     * 通过Id查询数据
     */
    public void findById(){
        Integer id=getParaToInt("id");
        Record record=DaoFactory.getUserDao().findModulesById(id);
        if(record==null){
            Map<String,Object>map=new HashMap<String, Object>();
            map.put("id", 0);
            map.put("search_module_name", "");
            map.put("search_key", "");
            map.put("tender_type",0);
            map.put("item_amount", 0);
            map.put("is_overdue", 0);
            map.put("search_type", 1);
            map.put("search_subscriber", "");
            map.put("qualification_id", 0);
            setAttr("shi", 0);
            setAttr("shen", 0);
            setAttr("module",map);

        }else {
//            查询地域层级
            int location = record.getInt("location_id");
            Record loca = DaoFactory.getLocationDao().findLevel(location);
            if (loca != null) {
//            Record rc=DaoFactory.getLocationDao().findById(loca.getInt("parentid"));
//            if(rc!=null) {
//                loca.set("pid", rc.get("code"));
//            }
                if (loca.getInt("parentid") == 0) {
                    setAttr("shen", loca.get("code"));
                    setAttr("shi", 0);
                } else {
                    setAttr("shi", loca.get("code"));
                    Record re = DaoFactory.getLocationDao().findById(loca.getInt("parentid"));
                    setAttr("shen", re.get("code"));
                }
            }
            setAttr("module", record);
        }
        render(new JsonRender().forIE());
    }

    /**
     * 修改模板
     */
    public void modul_update() {
        User user = (User) getSessionAttr("user");
        Integer id = getParaToInt("id", 0);
        String name_d=Jsoup.clean(getPara("name_d","".trim()), Whitelist.basic());
        String keyword_d=Jsoup.clean(getPara("keyword_d","").trim(), Whitelist.basic());
        Integer search_type_d = getParaToInt("search_type_d", 0);
        Integer tender_type_d = getParaToInt("tender_type_d", 0);
        Integer isOverdue_d = getParaToInt("isOverdue_d", 0);
        String search_subscriber_d=Jsoup.clean(getPara("search_subscriber_d","").trim(), Whitelist.basic());
        Integer location_d = getParaToInt("location_d", 0);
        Integer itemAmount_d = getParaToInt("itemAmount_d", 0);
        Integer qualification_d = getParaToInt("qualification_d", 0);
        if(name_d.length()>15){
            setAttr("msg",3);
            render(new JsonRender().forIE());
            return;
        }
//        影响行数为1时，表明修改成功
//        Record record = DaoFactory.getUserDao().findModulesByName(user.getInt("id"), name_d);
        Record record=DaoFactory.getUserDao().findModulesById(id);
       if (record != null) {
           if (record.getStr("search_module_name").equals(name_d)) {

               if (DaoFactory.getUserDao().updateModule(name_d, keyword_d, search_type_d, tender_type_d, isOverdue_d, search_subscriber_d
                       , location_d, itemAmount_d, qualification_d, id) == 1) {
                   setAttr("msg", 0);
               } else {
                   setAttr("msg", 1);
               }
           }else{
              Record record1= DaoFactory.getUserDao().findModulesByName(user.getInt("id"), name_d);
               if(record1!=null){
                   setAttr("msg",2);
               } else {
                   DaoFactory.getUserDao().updateModule(name_d, keyword_d, search_type_d, tender_type_d, isOverdue_d, search_subscriber_d
                           , location_d, itemAmount_d, qualification_d, id);
                   setAttr("msg", 0);
               }
           }
       }





        render(new JsonRender().forIE());
    }
    /**
     * 删除模板
     */
	public void deleteModule(){
        int id=getParaToInt("id",0);
        if(DaoFactory.getUserDao().deleteModule(id)){
            setAttr("msg",0);
        }else{
            setAttr("msg",1);
        }
        render(new JsonRender().forIE());
    }
}
